package com.zyy.joseata.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.zyy.joseata.socket.SocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * // 会影响原来的RabbitTemplate.convertAndSend()的数据发送
 * SimpleMessageConverter only supports String, byte[] and Serializable payloads, received: com.hoolink.iot.common.server.device.sound.api.SoundDataUpBO
 * @author zhangyy
 */
@Configuration
@Slf4j
public class JoSeataMqConfig {

    @Value("${spring.rabbitmq.host}")
    private String mqHost;

    @Value("${spring.rabbitmq.port:5672}")
    private Integer mqPort;

    @Value("${spring.rabbitmq.username:guest}")
    private String userName;

    @Value("${spring.rabbitmq.password:guest}")
    private String password;

    @Value("${spring.rabbitmq.virtual-host:/}")
    private String vHost;

    @Bean
    public ConnectionFactory connectionFactory(){
        ConnectionFactory  connectionFactory = new ConnectionFactory ();
        connectionFactory.setHost(mqHost);
        connectionFactory.setPort(mqPort);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(vHost);
        return connectionFactory;
    }

    @Bean
    public Connection mqConncetion(ConnectionFactory connectionFactory) throws IOException, TimeoutException {
        Connection connection = connectionFactory.newConnection();
        return connection;
    }

    /**
     * 设置消息监听的参数
     * @param
     * @return
     */
    @Bean
    public Channel mqChannel(Connection connection, SocketClient socketClient) throws IOException {
        Channel channel = connection.createChannel();
        channel.confirmSelect();
        channel.addConfirmListener(new JoSeataMqAck(socketClient));
        channel.addReturnListener(new JoSeataMqAck(socketClient));
        return channel;
    }

}
